package ex0;

import java.io.BufferedReader;
import java.io.FileReader;

/**
 * Created with IntelliJ IDEA.
 * User: Roy
 * Date: 10/17/13
 */
public class Ex0 {

	@SuppressWarnings("resource")
	public static void run(String[] args)
	{
		// make sure we get only one parameter - the file name
		if(args.length != 1)
            return;

        // get the filename
        String filename = args[0];
        try
        {
            // read the file
            BufferedReader reader = new BufferedReader(new FileReader(filename));
            String line;

            // for each line, convert a postﬁx expression to inﬁx form and evaluate the correct numerical value
            while ((line = reader.readLine()) != null)
            {
                Calc calc = new Calc();
                Calc.State curState = calc.process(line);
                if (curState.isError)
                    System.out.println(line + " : invalid expression");
                else
                {
                    String infixExp = curState.infixExpStack.pop();
                    int length = infixExp.length();

                    if(infixExp.charAt(0) == '(' && infixExp.charAt(length - 1) == ')')
                        infixExp = infixExp.substring(1, length - 1);

                    Double value = curState.valueStack.pop();
                    System.out.println(line + " : " + infixExp + " = " + value);
                }
            }
        }
        catch (Exception e)
        {
            System.err.format("Exception occurred trying to read '%s'.", filename);
            e.printStackTrace();
        }
	}
}
